const _ = require("lodash");
const statuses = require("statuses");
const userCodes = require("./codes");
const cryptoUtils = require("../crypto");

// 状态码不在系统状态内，且大于999小余100，认为是需要返回正确的状态数据给用户
const codes = _.merge(statuses, userCodes);
module.exports = {
  /**
   * @function status 根据code取状态码对应的message
   * @param {Number} code
   */
  status(code) {
    return codes[code];
  },

  /**
   * @function respond 构造响应body
   * @param {Object} data
   * @param {String} message
   * @param {Number} status
   */
  respond(data, status, message, isDecrypt) {
    data = data || undefined; // 解决data为null或者undefined
    status = status || 0; // 解决status为null或者undefined
    message = message || this.status(status) || "未知错误";
    return {
      data,
      status,
      message,
      isDecrypt,
    };
  },
  respondBody(ctx) {
    return (data, status, message) => {
      ctx.body = this.respond(data, status, message);
    };
  },
  respondBodyEncrypt(ctx) {
    const {
      config,
      app: { env },
    } = ctx;
    if (env === "development") {
      return this.respondBody(ctx);
    }
    return (data, status, message) => {
      const aesData = typeof data === "object" ? JSON.stringify(data) : data;
      const strData = cryptoUtils.encryptAesMix(aesData, config.aes);
      ctx.body = this.respond(strData, status, message, true);
    };
  },
};
